package com.test;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.Semaphore;
import java.util.stream.IntStream;

/**
 * 信号量实现的多线程操作
 */
@Slf4j
public class SemaphoreMTMain {

    /**
     * 信号量为5的公平锁
     */
    private static Semaphore semaphore = new Semaphore(5, true);

    public static void main(String[] args) {
        try {
            IntStream.range(0, 30).parallel().forEach(i -> {
                try {
//                     log.info(i + "开始新任务前：" + semaphore.availablePermits() + " _ " + semaphore.getQueueLength());
                    if (semaphore.availablePermits() == 0) {
                        log.info(i + "没有可用信号量，等待中...");
                    }
                    semaphore.acquire();
//                     log.info(i + "开始新任务后：" + semaphore.availablePermits() + " _ " + semaphore.getQueueLength());
                    log.info("开始执行 " + i);
                    // 模拟程序执行耗时
                    Thread.sleep(5L);
                } catch (Throwable e) {
                    e.printStackTrace();
                } finally {
                    semaphore.release();
//                     log.info(i + "执行任务后：" + semaphore.availablePermits() + " _ " + semaphore.getQueueLength());
                    log.info("执行完 " + i);
                }
            });
        } catch (Throwable e) {
            log.info("异常：", e);
        } finally {
            log.info("结束");
        }
        log.info("end");
    }

}
